package com.sk.sourcecircle.activity.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.adapter.ConsultCommentAdapter;
import com.sk.sourcecircle.adapter.SimalConsultAdapter;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.dialog.ShareDialogFragment;
import com.sk.sourcecircle.entity.NoticeDetailsInfo;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;

import org.sufficientlysecure.htmltextview.HtmlHttpImageGetter;
import org.sufficientlysecure.htmltextview.HtmlTextView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/12/26.
 */

public class DetailsOfConsultationActivity extends BaseActivity implements HandleDataCallBack, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.html_text)
    HtmlTextView htmlText;
    @BindView(R.id.line3)
    View line3;
    @BindView(R.id.data_ryc)
    RecyclerView dataRyc;
    @BindView(R.id.comment_ryc)
    RecyclerView commentRyc;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.ed_comment)
    EditText edComment;
    @BindView(R.id.add_collect)
    ImageView addCollect;
    @BindView(R.id.cancel_collect)
    ImageView cancelCollect;

    private int id;
    private LoadingDialog loadingDialog;
    private String comment = "";
    private List<NoticeDetailsInfo.DataBean.SimilarListBean> similarListBeanList = new ArrayList<>();
    private List<NoticeDetailsInfo.DataBean.CommentListBean> commentListBeanList = new ArrayList<>();
    private SimalConsultAdapter simalConsultAdapter;
    private ConsultCommentAdapter consultCommentAdapter;
    private NoticeDetailsInfo.DataBean bean;


    @Override
    protected int getContentView() {
        return R.layout.activity_details_of_consult;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        loadingDialog.show();
        id = getIntent().getIntExtra("id", 0);

        dataRyc.setLayoutManager(new LinearLayoutManager(mContext));
        simalConsultAdapter = new SimalConsultAdapter(R.layout.item_link_consult, similarListBeanList);
        View emptyView = getLayoutInflater().inflate(R.layout.empty_view, null);
        simalConsultAdapter.setEmptyView(emptyView);
        dataRyc.setAdapter(simalConsultAdapter);
        simalConsultAdapter.setOnItemClickListener(this);

        commentRyc.setLayoutManager(new LinearLayoutManager(mContext));
        consultCommentAdapter = new ConsultCommentAdapter(R.layout.item_comment_ryc, commentListBeanList);
        View emptyView1 = getLayoutInflater().inflate(R.layout.empy_comment_view, null);
        consultCommentAdapter.setEmptyView(emptyView1);
        commentRyc.setAdapter(consultCommentAdapter);


        dataRyc.setHasFixedSize(true);
        dataRyc.setNestedScrollingEnabled(false);

        commentRyc.setHasFixedSize(true);
        commentRyc.setNestedScrollingEnabled(false);


        edComment.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    if (edComment.getText().toString().length() > 0) {
                        loadingDialog.show();
                        comment = edComment.getText().toString();
                        AppApi.postComment(edComment.getText().toString(), "3", id, DetailsOfConsultationActivity.this, 2, DetailsOfConsultationActivity.this);
                    } else {
                        SnackUtils.showError(mRootView,"发送的消息不能为空哦~");
                    }
                }
                return false;
            }
        });

        AppApi.getNoticeDetails(id, this, 0, this);
    }

    @OnClick(R.id.back)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 0:
                NoticeDetailsInfo noticeDetailsInfo = JSON.parseObject(result, NoticeDetailsInfo.class);
                bean = noticeDetailsInfo.getData();
                htmlText.setHtml(bean.getContent(), new HtmlHttpImageGetter(htmlText, null, true));
                tvTitle.setText(noticeDetailsInfo.getData().getTitle());
                tvTime.setText(noticeDetailsInfo.getData().getCreate_time());

                if (noticeDetailsInfo.getData().getIs_favorite() == 1) {
                    cancelCollect.setVisibility(View.VISIBLE);
                    addCollect.setVisibility(View.GONE);
                } else {
                    cancelCollect.setVisibility(View.GONE);
                    addCollect.setVisibility(View.VISIBLE);
                }

                similarListBeanList.addAll(noticeDetailsInfo.getData().getSimilar_list());
                simalConsultAdapter.notifyDataSetChanged();
                commentListBeanList.addAll(noticeDetailsInfo.getData().getComment_list());
                consultCommentAdapter.notifyDataSetChanged();

                break;
            case 2:
                loadingDialog.cancelDialog();
                edComment.setText("");
                NoticeDetailsInfo.DataBean.CommentListBean commentListBean = new NoticeDetailsInfo.DataBean.CommentListBean();
                commentListBean.setContent(comment);
                DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                commentListBean.setCreate_time(fmt.format(curDate));
                NoticeDetailsInfo.DataBean.CommentListBean.UserBean userBean = new NoticeDetailsInfo.DataBean.CommentListBean.UserBean();
                userBean.setHead_url(MyUtils.getMyInfo(mContext).getHead_url());
                userBean.setNickname(MyUtils.getMyInfo(mContext).getNickname());
                commentListBean.setUser(userBean);
                commentListBeanList.add(commentListBean);
                consultCommentAdapter.notifyDataSetChanged();
                SnackUtils.show(mRootView,"评论成功了哦~");
                break;
            case 5:
                loadingDialog.cancelDialog();
                cancelCollect.setVisibility(View.VISIBLE);
                addCollect.setVisibility(View.GONE);
                SnackUtils.show(mRootView,"添加收藏成功了~");
                break;
            case 6:
                loadingDialog.cancelDialog();
                cancelCollect.setVisibility(View.GONE);
                addCollect.setVisibility(View.VISIBLE);
                SnackUtils.show(mRootView,"取消收藏成功~");
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();

    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();

    }

    @OnClick({R.id.add_collect, R.id.cancel_collect, R.id.share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_collect:
                loadingDialog.show();
                AppApi.addCollect(id, 2, DetailsOfConsultationActivity.this, 5, DetailsOfConsultationActivity.this);
                break;
            case R.id.cancel_collect:
                loadingDialog.show();
                AppApi.cancelCollect(id, 2, DetailsOfConsultationActivity.this, 6, DetailsOfConsultationActivity.this);
                break;

            case R.id.share:
                String summary = String.valueOf(Html.fromHtml(bean.getContent(), null, null));
                ShareDialogFragment shareDialogFragment = new ShareDialogFragment();
                shareDialogFragment.setImageUrl(bean.getHead_url());
                shareDialogFragment.setSummary(summary);
                shareDialogFragment.setTitle(bean.getTitle());
                shareDialogFragment.setTargetUrl("https://appdev.qigle.com/yuanquan/share/share/getArticle?id=" + bean.getArticle_id());
                shareDialogFragment.show(getFragmentManager(), "share");
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter instanceof SimalConsultAdapter) {
            Intent intent = new Intent(mContext, DetailsOfConsultationActivity.class);
            intent.putExtra("id", similarListBeanList.get(position).getArticle_id());
            startActivity(intent);
        }
    }
}
